import 'dart:io';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../provider/AuthProvider.dart';
import '../provider/post_list_provider.dart';
import '../widgets/publish_success_ani.dart';
import 'post_rent.dart';

class ComplaintPublishPage extends StatefulWidget {
  const ComplaintPublishPage({Key? key}) : super(key: key);

  @override
  State<ComplaintPublishPage> createState() => _ComplaintPublishPageState();
}

class _ComplaintPublishPageState extends State<ComplaintPublishPage> {
  final _formKey = GlobalKey<FormState>();
  final _picker = ImagePicker();

  String _title = '';
  String _content = '';
  List<File> _images = [];

  Future<void> _pickImages() async {
    final pickedFiles = await _picker.pickMultiImage(imageQuality: 70);
    if (pickedFiles.isNotEmpty) {
      setState(() {
        _images.addAll(pickedFiles.map((e) => File(e.path)));
        if (_images.length > 5) {
          _images = _images.sublist(0, 5);
        }
      });
    }
  }

  void _removeImage(int index) {
    setState(() {
      _images.removeAt(index);
    });
  }

  void _submit() async {
    if (!_formKey.currentState!.validate()) return;
    _formKey.currentState!.save();

    bool success = await RentPublishPage.publishPost(
      type: 'rant',
      title: _title,
      content: _content,
      images: _images,
      location: '',
    );

    if (success && mounted) {
      final currentContext = context; // 缓存 context，防止后续异步失效
      WidgetsBinding.instance.addPostFrameCallback((_) {
        PublishSuccessOverlay.show(
          currentContext,
          onComplete: () {
            // 动画结束后跳转首页，并刷新帖子列表
            WidgetsBinding.instance.addPostFrameCallback((_) {
              // 先刷新帖子列表数据
              final provider = Provider.of<PostListProvider>(
                currentContext,
                listen: false,
              );
              provider.fetchPosts(reset: true);
              // 使用 go_router 进行跳转
              final loggedIn = Provider.of<AuthProvider>(
                context,
                listen: false,
              ).isLoggedIn;
              print('动画完成，登录状态：$loggedIn');
              GoRouter.of(context).go('/?tab=home');
            });
          },
        );
      });
    } else if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('发布失败，请重试')));
    }
  }

  Widget _buildImagePicker() {
    return Wrap(
      spacing: 12,
      runSpacing: 12,
      children: [
        ..._images.asMap().entries.map((entry) {
          final idx = entry.key;
          final file = entry.value;
          return Stack(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Image.file(
                  file,
                  width: 100,
                  height: 100,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                top: -6,
                right: -6,
                child: IconButton(
                  icon: const Icon(Icons.cancel, color: Colors.redAccent),
                  onPressed: () => _removeImage(idx),
                  splashRadius: 18,
                ),
              ),
            ],
          );
        }),
        if (_images.length < 5)
          GestureDetector(
            onTap: _pickImages,
            child: Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: Colors.grey.shade200,
                borderRadius: BorderRadius.circular(10),
              ),
              child: const Icon(
                Icons.add_a_photo,
                color: Colors.grey,
                size: 30,
              ),
            ),
          ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('发布吐槽'), elevation: 0),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(), // 点击空白收起键盘
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题输入
                TextFormField(
                  initialValue: "",
                  decoration: InputDecoration(
                    hintText: '吐槽标题（必填）',
                    filled: true,
                    fillColor: Colors.grey.shade100,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 14,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(14),
                      borderSide: BorderSide.none,
                    ),
                  ),
                  maxLength: 50,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                  validator: (value) =>
                      value == null || value.trim().isEmpty ? '请输入标题' : null,
                  onSaved: (value) => _title = value!.trim(),
                ),

                const SizedBox(height: 20),

                // 内容输入
                TextFormField(
                  decoration: InputDecoration(
                    hintText: '吐槽内容，尽情表达你的不满吧...',
                    filled: true,
                    fillColor: Colors.grey.shade100,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 14,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(14),
                      borderSide: BorderSide.none,
                    ),
                  ),
                  maxLines: 6,
                  maxLength: 500,
                  validator: (value) =>
                      value == null || value.trim().isEmpty ? '请输入吐槽内容' : null,
                  onSaved: (value) => _content = value!.trim(),
                ),

                const SizedBox(height: 20),

                Text(
                  '上传图片（最多5张）',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    color: Colors.grey.shade700,
                    fontSize: 14,
                  ),
                ),

                const SizedBox(height: 12),

                _buildImagePicker(),

                const SizedBox(height: 36),

                SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: ElevatedButton(
                    onPressed: _submit,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.deepOrangeAccent,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                      elevation: 4,
                      shadowColor: Colors.deepOrangeAccent.withOpacity(0.4),
                    ),
                    child: const Text(
                      '发布吐槽',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
